package com.wss.lsl.mongo.demo;

import java.net.UnknownHostException;
import java.util.Set;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;

/**
 * Hello world!
 * 
 */
public class App {
	
	public static void main(String[] args) throws UnknownHostException {
		
		MongoClient mongoClient = new MongoClient("localhost", 27017);
		DB db = mongoClient.getDB("test");
		if(db.authenticate("wss", "wss".toCharArray())){
			Set<String> collections = db.getCollectionNames();
			for(String collectionName : collections){
				System.out.println(collectionName);
			}
			
			DBCollection table = db.getCollection("users");
			
			// insert
			BasicDBObject object = new BasicDBObject();
			object.put("username", "魏升水");
			object.put("password", "password");
			table.insert(object);
			object = new BasicDBObject();
			object.put("username", "mkyong");
			object.put("password", "123456");
			table.insert(object);
			
			// update
			final BasicDBObject query = new BasicDBObject();
			query.put("username", "mkyong");
			BasicDBObject newRecord = new BasicDBObject();
			newRecord.put("password", "654321");
			BasicDBObject updatedRecord = new BasicDBObject();
			updatedRecord.put("$set", newRecord);
			table.update(query, updatedRecord);
			
			// find
			DBCursor cursor = table.find(query);
			while(cursor.hasNext()){
				System.out.println(cursor.next());
			}
			
			// find all
			System.out.println();
			System.out.println("find all");
			cursor = table.find();
			while(cursor.hasNext()){
				System.out.println(cursor.next());
			}
			
			// delete
			table.remove(query);
			
			// find all
			System.out.println();
			System.out.println("find all");
			cursor = table.find();
			while(cursor.hasNext()){
				System.out.println(cursor.next());
			}
			
			table.remove(new BasicDBObject());
			
		}
		
		System.out.println("Done");
		
	}
}
